//
//  ReceiveViewModel.m
//  YKMediator_ReceiveModule
//
//  Created by linghit on 2021/8/17.
//

#import "ReceiveViewModel.h"
#import "ReceiveModel.h"
#import <SDWebImage/SDWebImage.h>
#import <YK_BaseTools/MQManager.h>
#import <YK_ExectionModel/YKConst.h>

@interface ReceiveViewModel ()<MQManagerDelegate>
///
@property (nonatomic,strong) MQManager *mqmanager;

@property (nonatomic, copy,readwrite) NSString *uid;

///
@property (nonatomic, strong, readwrite) NSMutableArray *lists;

@property (nonatomic, copy) NSString *comId;

@property (nonatomic, strong, readwrite) RACCommand *listCommand;
///
@property (nonatomic,strong, readwrite) RACCommand *saveCommand;
///
@property (nonatomic,strong, readwrite) RACCommand *userInfoCommand;
///
@property (nonatomic, strong, readwrite) RACCommand *uploadCellCommand;
///
@property (nonatomic, strong, readwrite) RACSubject *refreshSubject;
///
@property (nonatomic, assign, readwrite) NSInteger second;

@end

@implementation ReceiveViewModel

- (instancetype)initWithToken:(NSString *)token platform:(NSString *)platform comId:(NSString *)comId
{
    self = [super init];
    if (self) {
        [self configToken:token platform:platform comId:comId];
    }
    return self;
}

- (void)configToken:(NSString *)token platform:(NSString *)platform comId:(NSString *)comId
{
    self.comId = comId;
    self.netWorking.prefixUrl = @"http://8wfb3aq27y.52http.tech/";
    self.netWorking.dynamicHeaderConfig = ^NSDictionary * _Nonnull(YKNetworkRequest * _Nonnull request) {
        return @{@"token":token,@"platform":platform};
    };
    self.netWorking.dynamicParamsConfig = ^NSDictionary * _Nonnull(YKNetworkRequest * _Nonnull request) {
        return @{};
    };
    self.netWorking.handleResponse = ^NSError * _Nonnull(YKNetworkResponse * _Nonnull response, YKNetworkRequest * _Nonnull request) {
        	
        if (![response.rawData isKindOfClass:NSDictionary.class]) {
            NSLog(@"%@",NSStringFromClass(response.rawData));
            return nil;
        }
        
        NSDictionary *dic = response.rawData?:@{};
        NSInteger code = [dic[@"code"]?:@"0" integerValue];
        NSString *message = dic[@"message"]?:@"";
        id info = dic[@"info"];
        if (code > 4000 && code < 5000) {
            return [NSError errorWithDomain:@"YKReceive" code:code userInfo:@{
                NSLocalizedDescriptionKey:message,
            }];
        }else{
            response.rawData = info;
        }
        return nil;
//        return nil;
    };
    self.mqmanager = [MQManager loginUser:@"root" password:@"root" path:@"106.55.12.108:5672" routingKeys:@[
        [MQKey createMqKey:@[@"com",@"yk",@"receive",@"post",@"*"]],
    ] delegate:self];
    [self.mqmanager getMsg];
    [[RACSignal merge:@[
        self.listCommand.errors,
        self.saveCommand.errors,
        self.userInfoCommand.errors,
        self.uploadCellCommand.errors,
    ]] subscribe:self.errorSubject];
    self.second = [[NSDate date] timeIntervalSince1970];
}

- (void)getDetail:(NSIndexPath *)indexPath detailBlock:(void(^)(NSString *Id,NSMutableAttributedString *detailName,NSMutableAttributedString *price,NSString *createTime,BOOL isCell,NSMutableAttributedString *cellName,NSMutableAttributedString *collcetionName,NSString *title))detailBlock
{
    if (detailBlock) {
        ReceiveModel *model = self.lists[indexPath.row];
        NSString *Id = model.Id;
        
        NSString *detailName = [NSString stringWithFormat:@"商品备注:%@",model.cashier_name];
        NSMutableAttributedString *detailAttr = [[NSMutableAttributedString alloc] initWithString:detailName];
        [detailAttr addAttributes:@{
            NSForegroundColorAttributeName:[UIColor redColor],
        } range:[detailName rangeOfString:model.cashier_name]];
        
        NSString *price = [NSString stringWithFormat:@"商品价格:%@",model.cashier_price];
        NSMutableAttributedString *priceAttr = [[NSMutableAttributedString alloc] initWithString:price];
        [priceAttr addAttributes:@{
            NSForegroundColorAttributeName:[UIColor redColor],
        } range:[price rangeOfString:model.cashier_price]];
        
        NSString *createTime = model.create_at;
        BOOL isCell = [model.isSell?:@"0" boolValue];
        
        NSString *cellName = [NSString stringWithFormat:@"售货员:%@",model.cc_name?:@""];
        NSMutableAttributedString *cellAttr = [[NSMutableAttributedString alloc] initWithString:cellName];
        
        NSString *collcetionName = [NSString stringWithFormat:@"收款员:%@",model.re_name?:@""];
        NSMutableAttributedString *collectionAttr = [[NSMutableAttributedString alloc] initWithString:collcetionName];
        
        detailBlock(Id,detailAttr,priceAttr,createTime,isCell,cellAttr,collectionAttr,[NSString stringWithFormat:@"%@(%@元)",model.cashier_name,model.cashier_price]);
    }
}

- (RACCommand *)listCommand
{
    if (!_listCommand) {
        @weakify(self);
        _listCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [self.netWorking.get(@"/cashier/list").params(@{@"comId":@"3123"}).executeSignal.mapWithRawData map:^id _Nullable(id  _Nullable value) {
                
                NSArray<ReceiveModel *> *list = [ReceiveModel mj_objectArrayWithKeyValuesArray:value[@"lists"][@"data"]];
                
                [self handlePageData:self.lists newDatas:list];
                
                return @(list.count);
            }];
        }];
    }
    return _listCommand;
}

- (RACCommand *)uploadCellCommand
{
    if (!_uploadCellCommand) {
        @weakify(self);
        _uploadCellCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            NSString *name = input[@"name"];
            if (name.length <= 0) {
                name = @"销售商品";
            }
            
            NSString *price = input[@"price"];
            if (price.length <= 0) {
                
                return [RACSignal error:YKError(@"请输入价格")];
            }
            
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setValue:self.comId?:@"" forKey:@"complateId"];
            [params setValue:name forKey:@"name"];
            [params setValue:price forKey:@"price"];
            
            return [self.netWorking.post(@"/cashier/add").params(params.copy).executeSignal.mapWithRawData map:^id _Nullable(id  _Nullable value) {
                
                [self.mqmanager sendNorMsg:[NSString stringWithFormat:@"创建了-name:%@-price:%@",name,price] key:[MQKey createMqKey:@[@"com",@"yk",@"receive",@"post",@"1"]]];
                
                return @(YES);
            }];
        }];
    }
    return _uploadCellCommand;
}

- (RACCommand *)saveCommand
{
    if(!_saveCommand)
    {
        @weakify(self);
        _saveCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            NSString *Id = input;
            if (Id.length <= 0) {
                return [RACSignal error:YKError(@"数据错误")];
            }
            return  [self.netWorking.post(@"/cashier/sell").params(@{@"id":Id}).executeSignal.mapWithRawData doNext:^(id  _Nullable x) {
                @strongify(self);
            }];
            
        }];
    }
    return _saveCommand;
}

- (RACCommand *)userInfoCommand
{
    if(!_userInfoCommand)
    {
        @weakify(self);
        _userInfoCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return  [self.netWorking.get(@"user/info").executeSignal.mapWithRawData map:^id _Nullable(id  _Nullable value) {
                
                self.uid = value[@"u_id"]?:@"";
                
                return value;
            }];
            
        }];
    }
    return _userInfoCommand;
}

- (NSMutableArray *)lists
{
    if (!_lists) {
        _lists = [NSMutableArray array];
    }
    return _lists;
}

- (RACSubject *)refreshSubject
{
    if (!_refreshSubject) {
        _refreshSubject = [RACSubject subject];
    }
    return _refreshSubject;
}


- (void)mqmanager:(MQManager *)manager receiveMessageData:(NSData *)receiveMessageData routingKey:(NSString *)routingKey consumerTag:(NSString *)consumerTag exchangeName:(NSString *)exchangeName receiveDate:(NSString *)receiveDate
{
    if ([routingKey isEqualToString:@"com.yk.receive.post.1"]) {
        NSInteger second = [[NSDate date] timeIntervalSince1970];
        if ((second - self.second)>5) {
            self.second = second;
            [self.refreshSubject sendNext:@""];
        }
    }
}

- (void)mqmanager:(MQManager *)manager recoveredConnectionType:(MQManagerRecoveredType)recoveredConnectionType
{
    
}

- (void)mqmanager:(MQManager *)manager onError:(NSError *)error errorType:(MQManagerErrorType)errorType
{
    [self.errorSubject sendNext:error];
}


@end
